﻿using Microsoft.Extensions.DependencyInjection;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Caching;
using PmSoft.DBContext;
using PmSoft.Repositories;

namespace Modules.Audit.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class SysAuditLogRepository : Repository<SysAuditLog, DefaultDbContext>
    {
        public SysAuditLogRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
        {
        }

        public IEnumerable<SysAuditLog> GetAuditLogsByObjectId(int objectId, string tableName)
        {
            int areaVersion = EntityCacheService.GetAreaVersion("ObjectId", objectId);
            return GetTopEntities(1000, CachingExpirationType.ObjectCollection, () =>
            {
                return $"AuditLogsByObjectId:{objectId}:{areaVersion}";
            }, () =>
            {
                Sql sql = Sql.Builder
                .Select("id")
                .From("sys_audit_log")
                .Where("object_id=@0 AND table_name=@1", objectId, tableName);
                return sql;
            });
        }

        public SysAuditLog? GetLastSysAuditLogByTableAndObjectId(string tableName, int objectId)
        {
            Sql sql = Sql.Builder.Select("id").From("sys_audit_log").Where("table_name=@0 AND object_id=@1", tableName, objectId)
                .OrderBy("sort desc");
            var id = DbContext.FirstOrDefault<int>(sql);
            if (id == 0)
                return null;
            return Get(id);
        }
    }
}